package org.rsbot.injector.adapters;

import org.rsbot.injector.data.MasterSetterData;
import org.rsbot.loader.asm.ClassAdapter;
import org.rsbot.loader.asm.ClassWriter;
import org.rsbot.loader.asm.MethodAdapter;
import org.rsbot.loader.asm.MethodVisitor;
import org.rsbot.loader.asm.Opcodes;

/**
 * @author Nader Sleiman
 */
public class MasterHackAdapter extends ClassAdapter implements Opcodes {

    MasterSetterData md;

    class MasterMethodAdapter extends MethodAdapter {

        private MasterSetterData md;

        public MasterMethodAdapter(MethodVisitor mv, MasterSetterData md) {
            super(mv);
            this.md = md;
        }

        @Override
        public void visitMethodInsn(int opcode, String owner, String name, String desc) {

            super.visitMethodInsn(opcode, owner, name, desc);
            if (name.equals("setBounds")) {
                super.visitVarInsn(ALOAD, md.aload);
                super.visitVarInsn(ILOAD, md.master_x_iload);
                super.visitFieldInsn(PUTFIELD, md.interface_name, md.master_x_name, "I");
                super.visitVarInsn(ALOAD, md.aload);
                super.visitVarInsn(ILOAD, md.master_y_iload);
                super.visitFieldInsn(PUTFIELD, md.interface_name, md.master_y_name, "I");
            }
        }
    }

    public MasterHackAdapter(ClassWriter cw, MasterSetterData md) {
        super(cw);
        this.md = md;
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
        if (mv != null && name.equals(md.method_name) && desc.equals(md.method_desc)) {
            mv = new MasterMethodAdapter(mv, md);
        }

        return mv;

    }
}
